import React, { useState, useEffect } from 'react';
import { Button, Table, Input, Space, Modal, Form, Select, message, TreeSelect } from 'antd';
import type { TableColumnsType } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import styles from './index.less';
import { getRole, getRoleLimits, addRole, deleteRole, getLimits, setRoleLimits } from '@/api/services';
import { Checkbox, Divider } from 'antd';
import { CheckboxValueType } from 'antd/lib/checkbox/Group';
import { getUserLimits } from "../../api/services";

const CheckboxGroup = Checkbox.Group;

const RoleMangement: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [data, setData] = useState([]);
  const [modalOpen, setModalOpen] = useState<boolean>(false);
  const [limitModal, setLimitModal] = useState<any>(false);
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const [roleId, setRoleId] = useState('');
  const [limits, setLimits] = useState<any>([]);
  const [checkedList, setCheckedList] = useState<string[]>([]);
  const [roleName, setRoleName] = useState<string>('');

  useEffect(() => {
    getLimits().then((res: any) => {
      if (res.status == 200) {
        console.log(res);
        setLimits(res.results);
      }

    })
  }, [])

  const options: any = limits.map((parent: any) => ({
    label: parent.authority_title,
    options: (parent.authorities || []).map((child: any) => ({
      label: child.authority_name,
      value: child.authority_id.toString(),
    })),
  }));

  console.log(options);

  const onChange = (list: any) => {

    console.log(list)
  };


  const onItemChange = (parentIndex: any, itemValue: any) => {
    console.log(parentIndex);
    console.log(typeof (itemValue));
    let flag = checkedList.includes(itemValue);
    console.log(flag)
    if (!flag) {
      setCheckedList([...checkedList, itemValue]);
    } else {
      const arr = checkedList.filter(function (item) {
        return item !== itemValue;
      })
      setCheckedList(arr)
    }
  };

  // 默认选中的权限
  const defaultCheckedList = limits.map((parent: any) => parent.authorities.map((child: any) => child.authority_id.toString())).flat();

  const onSelectChange = (newSelectedRowKeys: any) => {
    setSelectedRowKeys(newSelectedRowKeys);
    setRoleId(newSelectedRowKeys[0]);
    const selectedRows: any = data.filter((row: any) => newSelectedRowKeys.includes(row.key));
    // console.log('选中的行信息：', selectedRows[0].role_desc);
    setRoleName(selectedRows[0].role_desc);
  };

  const rowSelection = {
    type: 'radio',
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;

  const getRoleList = () => {
    getRole({
      page: page,
      size: 10,
    }).then((res: any) => {
      if (res.status == 200) {
        const newData = res.results.map((item: any) => {
          return { ...item, key: item.role_id };
        });
        setData(newData);
        setTotal(res.length);
      }

    })
  }

  useEffect(() => {
    getRoleList();
  }, [page]);




  //新增角色
  const addUserList = async () => {
    const validate = await form.validateFields();
    addRole({
      type: validate.role_type,
      // pwd: validate.user_pwd,
      desc: validate.role_desc,
    }).then((res: any) => {
      if (res.status == 200) {
        console.log(res);
        message.success('新增成功');
        setModalOpen(false);
        getRoleList();
      }

    })
  }

  //获取对应角色权限
  const getRoleLimitsList = () => {
    if (!roleId) {
      message.info('请先选择角色');
      return;
    }
    setLimitModal(true);
    getRoleLimits({
      roleId: roleId
    }).then((res: any) => {
      if (res.status == 200) {
        const array = res.results[0].authority_id?.split(",");
        console.log(array)
        setCheckedList(array);
      }


    })
  }

  //设置权限
  const setLimit = async () => {
    console.log(checkedList)
    const validate = await form1.validateFields();
    // console.log('111', validate);
    setRoleLimits({
      roleId: roleId,
      authority: checkedList.toString(),
    }).then((res: any) => {
      if (res.status == 200) {
        console.log(res);
        message.success('编辑成功');
        getUserLimits({
          roleId: JSON.parse(localStorage.getItem("user") as any).user_roleid
        }).then((res: any) => {
          if (res.status == 200) {
            console.log(res);
            localStorage.setItem('admitRequest', res.admitRequest);
          }
        })
        getRoleList();
        setLimitModal(false);
      }
    })
  }

  //删除用户
  const delRoleList = (id: any) => {
    console.log('id', id);
    deleteRole({
      roleId: id
    }).then((res: any) => {
      if (res.status == 200) {
        console.log(res);
        message.success('删除成功');
        getRoleList();
      }
    })
  }

  const columns = [

    {
      title: '角色类型',
      dataIndex: 'role_type',
    },
    {
      title: '角色描述',
      dataIndex: 'role_desc'
    },
    {
      title: 'Action',
      dataIndex: '',
      key: 'x',
      render: (text: any, record: any) =>
        <Space size="middle">
          <a onClick={() => { delRoleList(record.role_id) }}>删除</a>
        </Space>
    },
  ];

  const paginationConfig = {
    total: total,
    onChange: (page: number, pageSize?: number) => {
      setPage(page);
    },
    showTotal: (total: number, range: [number, number]) => `共 ${total} 条数据`,
  }

  const ModalFooter = (
    <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
      <Button
        type="primary"
        style={{ marginRight: 16, borderRadius: 6 }}
        onClick={addUserList}
      >
        确定
      </Button>
      <Button
        style={{ marginRight: 16, borderRadius: 6 }}
        onClick={() => { setModalOpen(false) }}
      >
        取消
      </Button>
    </div>
  )


  return (
    <div className={styles.orderContainer}>

      <div className={styles.header}>

        <Button type="primary" style={{ marginRight: 20 }}
          onClick={() => {
            setModalOpen(true);
            form.resetFields();
          }}
        >创建角色</Button>
        <Button type="primary"
          onClick={() => {
            getRoleLimitsList()
          }}
        >设置权限</Button>
      </div>
      <Table rowSelection={rowSelection} columns={columns} dataSource={data} pagination={paginationConfig} />
      {modalOpen &&
        <Modal
          open={modalOpen}
          title="新增角色"
          onCancel={() => { setModalOpen(false) }}
          footer={ModalFooter}
        >
          <Form
            form={form}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 14 }}
          >
            <Form.Item label="角色名称" name="role_type">
              <Input />
            </Form.Item>
            <Form.Item label="角色描述" name="role_desc">
              <Input />
            </Form.Item>
          </Form>
        </Modal>
      }
      {
        limitModal &&
        <Modal
          title="设置权限"
          open={limitModal}
          onCancel={() => { setLimitModal(false) }}
          footer={
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
              <Button
                type="primary"
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={setLimit}
              >
                确定
              </Button>
              <Button
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={() => { setLimitModal(false) }}
              >
                取消
              </Button>
            </div>
          }
        >
          <Form.Item label="角色名称" name="role_type">
            <Input defaultValue={roleName} disabled />
          </Form.Item>
          <Divider />


          {options.map((parent: any, parentIndex: any) => (
            <div key={parentIndex}>
              <h3>{parent.label}</h3>
              <Space size='middle'>
                <Checkbox.Group style={{ width: '100%' }} value={checkedList} onChange={onChange}>
                  {parent.options?.map((option: any, itemIndex: any) => (
                    <Checkbox
                      key={itemIndex}
                      value={option.value}
                      checked={checkedList.includes(option.value)}
                      onChange={() => onItemChange(parentIndex, option.value)}
                    >
                      {option.label}
                    </Checkbox>
                  ))}
                </Checkbox.Group>
              </Space>
            </div>
          ))}

        </Modal>
      }
    </div>
  );
};

export default RoleMangement;